// dragon/pages/dragonList/dragonList.js
const styleDefault = {
    width: "710rpx",
    height: "266rpx",
    onOff: false,
    //是否使用自定义指示点，false不使用
    type: 1,
    //只是点类型
    mainColor: "#000000",
    //主色
    subColor: "rgba(0, 0, 0, .3)",
    //辅助色
    autoplay: true,
    //是否自动播放
    duration: 500,
    //动画时间
    interval: 3e3,
    //动画间隔
    circular: true,
    //是否使用衔接滚动
    previous_margin: "0rpx",
    //前边距
    next_margin: "0rpx",
    //后边距
    display_multiple_items: 1
};

//默认样式
const app = getApp();

var common = require("../../../common/common.js").common;

var WxParse = require("../../../wxParse/wxParse.js");

var leader = require("../../../common/leader.js").leader;

var colorParse = require("../../../common/color.js");

var un = require("../../../siteinfo");

Page({
    /**
   * 页面的初始数据
   */
    data: {
        styleData: {
            ...styleDefault
        },
        current: 0,
        // swiper初始对应的swiper-item
        currentIndex: 0,
        // 用来记录当前swiper对应的索引index
        group_id: "",
        share: 0,
        myleaderinfo: {
            leader_id: -1,
            leader_id_true: -1
        }
    },
    /**
   * 生命周期函数--监听页面加载
   */
    onLoad: function(options) {
        let that = this;
        that.setData({
            domain: app.globalData.domain.slice(0, -10)
        });
        wx.hideShareMenu();
        wx.getSystemInfo({
            success: function(res) {
                let rpx = res.windowWidth / 375;
                that.setData({
                    rpx: rpx
                });
            }
        });
        that.getMyInfo();
        leader.getMyLeaderInfo_aync().then(() => {
            that.getSow();
            that.getBase();
            that.getGroupList();
            that.getGroupSet();
        });
    },
    /**
   * 生命周期函数--监听页面初次渲染完成
   */
    onReady: function() {},
    /**
   * 生命周期函数--监听页面显示
   */
    onShow: function() {
        leader.getMyLeaderInfo();
    },
    /**
   * 生命周期函数--监听页面隐藏
   */
    onHide: function() {},
    /**
   * 生命周期函数--监听页面卸载
   */
    onUnload: function() {},
    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
    onPullDownRefresh: function() {
        let that = this;
        leader.getMyLeaderInfo_aync().then(() => {
            that.getSow();
            that.getBase();
            that.getGroupList();
            that.getGroupSet();
        });
        wx.stopPullDownRefresh();
    },
    /**
   * 页面上拉触底事件的处理函数
   */
    onReachBottom: function() {},
    /**
   * 用户点击右上角分享
   */
    onShareAppMessage: function(e) {
        return {
            title: e.target.dataset.item.title,
            imageUrl: e.target.dataset.item.share_img,
            path: `/dragon/pages/dragonDetail/dragonDetail?id=${e.target.dataset.item.id}&leader_id_share=${this.data.myleaderinfo.leader_id}`
        };
    },
    //全局基础配置信息
    getBase: function(openid) {
        var that = this;
        common.request({
            endpoint: "set/app_base",
            method: "get",
            data: {},
            success: res => {
                that.setData({
                    color_header: res.extra.color_header,
                    color_text: res.extra.color_text,
                    color_main: res.extra.color_main,
                    color_minor: res.extra.color_minor,
                    title: res.extra.title,
                    style: res.extra.style,
                    leader_change: res.extra.l_change,
                    leaderName: res.extra.leader_title ? res.extra.leader_title : "团长",
                    is_open: res.extra.is_open,
                    copyImg: res.extra.copyright_img,
                    share_link: res.extra.share_link,
                    userAuditStatus: res.extra.userAuditStatus ? res.extra.userAuditStatus : 2
                });
            }
        });
    },
    groupSet: function() {},
    getMyInfo: function() {
        var that = this;
        var openid = wx.getStorageSync("user").openid;
        common.request({
            endpoint: "My/myinfo/myinfo",
            method: "post",
            data: {
                openid: openid
            },
            success: res => {
                console.log(res);
                that.setData({
                    info: res.extra
                });
            }
        });
    },
    getGroupList: function() {
        let that = this;
        common.request({
            endpoint: "group-solit/list",
            method: "post",
            data: {
                group_name: that.data.search_on,
                uniacid: un.uniacid,
                openid: wx.getStorageSync("user").openid
            },
            success: res => {
                if (res.code == 0) {
                    res.extra.forEach(item => {
                        item.pro_images = item.products.map(product => {
                            return product.icon;
                        });
                    });
                    that.setData({
                        groupList: res.extra
                    });
                    // var groupList=res.extra;
                    // var groupListArr=[]
                    // groupList.map((x,i)=>{
                    //   WxParse.wxParse('reply' + i, 'html', groupList[i].group.detail, that);
                    //   if (i === groupList.length - 1) {
                    //     WxParse.wxParseTemArray("WxParseListArr",'reply', groupList.length, that)
                    // }
                    // x.group.img= x.group.img.split(','); 
                    // if(((x.group.leader_show==1&&that.data.myleaderinfo.iam_leader==1)||(x.group.leader_show==0))&&(x.group.is_show==1)&&(x.group.status==1)){
                    //   groupListArr.push(x);
                    // }
                    // })
                    // that.setData({
                    //   groupList:groupListArr,
                    // })
                                        if (!that.data.groupList.length) {
                        wx.showToast({
                            icon: "none",
                            title: "暂无群接龙活动",
                            duration: 2e3
                        });
                        setTimeout(() => {
                            wx.switchTab({
                                url: "/pages/index/index"
                            });
                        }, 2e3);
                    }
                }
            },
            fail(res) {
                that.setData({
                    groupList: []
                });
                wx.showToast({
                    icon: "none",
                    title: res.message,
                    duration: 2e3
                });
                setTimeout(() => {
                    wx.switchTab({
                        url: "/pages/index/index"
                    });
                }, 2e3);
            }
        });
    },
    goToDetails: function(e) {
        common.request({
            endpoint: "group-solit/add-scan",
            method: "post",
            data: {
                group_id: e.currentTarget.dataset.id
            },
            success: res => {},
            fail() {}
        });
        wx.navigateTo({
            url: e.currentTarget.dataset.url
        });
    },
    saveInput: function(e) {
        let that = this;
        let value = e.detail.value;
        that.setData({
            search_on: value
        });
    },
    saveimgdo: function(e) {
        var that = this;
        console.log(123);
        wx.getSetting({
            success(res) {
                if (!res.authSetting["scope.writePhotosAlbum"]) {
                    wx.authorize({
                        scope: "scope.writePhotosAlbum",
                        success() {
                            that.dosave(e);
                        },
                        fail() {
                            wx.openSetting();
                            wx.showModal({
                                title: "提示",
                                content: "未授权相册，请删小程序后再试！"
                            });
                        }
                    });
                } else {
                    that.dosave(e);
                }
            }
        });
    },
    getSow: function() {
        var that = this;
        common.request({
            endpoint: "JumpLink/jump_link/link_object",
            method: "post",
            success: res => {
                that.setData({
                    group_solit: res.extra[0].group_solit
                });
            }
        });
    },
    getGroupSet: function() {
        var that = this;
        common.request({
            endpoint: "group-solit/group-set",
            method: "post",
            success: res => {
                var groupSet = res.extra;
                if (groupSet.poster.indexOf("https:") < 0) {
                    groupSet.poster = groupSet.poster.replace("http:", "https:");
                }
                that.setData({
                    groupSet: groupSet
                });
            }
        });
    },
    getQr: function(ctx, id, options) {
        var that = this;
        leader.getMyLeaderInfo_aync().then(() => {
            common.request({
                endpoint: "group-solit/poster-qr",
                method: "post",
                data: {
                    page: "dragon/pages/dragonDetail/dragonDetail",
                    group_id: id,
                    leader_id: that.data.myleaderinfo.leader_id
                },
                success: res => {
                    that.setData({
                        qr: res.extra
                    });
                    options.callback();
                },
                fail() {
                    options.callback();
                }
            });
        });
    },
    //跳转页面
    goToPages(e) {
        var that = this;
        common.getUserInfoNew({
            success() {
                wx.navigateTo({
                    url: e.currentTarget.dataset.pageurl
                });
            }
        });
    },
    //幻灯片切换
    swiperChange: function(e) {
        this.setData({
            currentIndex: e.detail.current
        });
    },
    hideShareModal: function() {
        this.setData({
            share: 0
        });
    },
    showShare: function(e) {
        let that = this;
        wx.showLoading({
            title: "分享图生成中..."
        });
        const ctx = wx.createCanvasContext("share_box");
        wx.getImageInfo({
            src: that.data.groupSet.poster,
            success(res) {
                ctx.drawImage(res.path, 0, 0, 375 * that.data.rpx, 667 * that.data.rpx);
                that.fillRoundRect(ctx, 12.5 * that.data.rpx, 518 * that.data.rpx, 352 * that.data.rpx, 139 * that.data.rpx, 2.5 * that.data.rpx, "#fff");
                wx.getImageInfo({
                    src: that.data.info.img,
                    success(res) {
                        ctx.save();
                        ctx.arc(45 * that.data.rpx, 559 * that.data.rpx, 21 * that.data.rpx, 0, 2 * Math.PI);
                        ctx.setFillStyle("#fff");
                        ctx.clip();
                        ctx.drawImage(res.path, 24 * that.data.rpx, 538 * that.data.rpx, 42 * that.data.rpx, 42 * that.data.rpx);
                        ctx.restore();
                        ctx.setFillStyle("#434343");
                        ctx.font = "14px Microsoft YaHei";
                        ctx.fillText(that.data.info.nickname, 77 * that.data.rpx, 557 * that.data.rpx);
                        ctx.setFillStyle("#939393");
                        ctx.font = "12px Microsoft YaHei";
                        ctx.fillText("邀请与您一起接龙购物", 77 * that.data.rpx, 577 * that.data.rpx);
                        that.strokeRoundRect(ctx, 77 * that.data.rpx, 588 * that.data.rpx, 97 * that.data.rpx, 24 * that.data.rpx, 1 * that.data.rpx, .5 * that.data.rpx, "#333333");
                        ctx.setFillStyle("#434343");
                        ctx.font = "12px Microsoft YaHei";
                        ctx.fillText("长按识别二维码", 86 * that.data.rpx, 605 * that.data.rpx);
                        that.getQr(ctx, e.currentTarget.dataset.id, {
                            callback() {
                                that.data.qr;
                                wx.getImageInfo({
                                    src: that.data.qr,
                                    success(res) {
                                        ctx.save();
                                        ctx.arc(280.5 * that.data.rpx, 582.5 * that.data.rpx, 60.5 * that.data.rpx, 0, 2 * Math.PI);
                                        ctx.setFillStyle("#fff");
                                        ctx.clip();
                                        ctx.drawImage(res.path, 220 * that.data.rpx, 522 * that.data.rpx, 121 * that.data.rpx, 121 * that.data.rpx);
                                        ctx.restore();
                                        ctx.draw(true, () => {
                                            var e = {
                                                currentTarget: {
                                                    dataset: {
                                                        type: "share"
                                                    }
                                                }
                                            };
                                            that.dosave(e);
                                        });
                                    },
                                    complete() {
                                        that.setData({
                                            share: 1,
                                            shareId: e.currentTarget.dataset.id
                                        });
                                    }
                                });
                            }
                        });
                    }
                });
            }
        });
    },
    dosave: function(e) {
        var that = this;
        wx.canvasToTempFilePath({
            x: 0,
            y: 0,
            width: 750 * that.data.rpx,
            height: 1337 * that.data.rpx,
            // destWidth: pwidth * pixelRatio,
            // destHeight: pheight * pixelRatio,
            canvasId: "share_box",
            success: function(res) {
                wx.hideLoading();
                if (e.currentTarget.dataset.type == "share") {
                    var prevList = [];
                    prevList.push(res.tempFilePath);
                    setTimeout(() => {
                        that.setData({
                            prevList: prevList
                        });
                    }, 500);
                } else if (e.currentTarget.dataset.type == "save") {
                    wx.saveImageToPhotosAlbum({
                        filePath: res.tempFilePath,
                        success: function(res) {
                            wx.showModal({
                                title: "提醒",
                                content: "请转发您专属的分享图至好友",
                                showCancel: false,
                                success: function(res) {}
                            });
                        },
                        fail: function(res) {
                            wx.hideLoading();
                            console.log("fail");
                        }
                    });
                }
            }
        });
    },
    /**该方法用来绘制一个有填充色的圆角矩形 
     *@param cxt:canvas的上下文环境 
     *@param x:左上角x轴坐标 
     *@param y:左上角y轴坐标 
     *@param width:矩形的宽度 
     *@param height:矩形的高度 
     *@param radius:圆的半径 
     *@param fillColor:填充颜色 
     **/
    fillRoundRect: function(cxt, x, y, width, height, radius, /*optional*/ fillColor) {
        //圆的直径必然要小于矩形的宽高          
        if (2 * radius > width || 2 * radius > height) {
            return false;
        }
        cxt.save();
        cxt.translate(x, y);
        //绘制圆角矩形的各个边  
                this.drawRoundRectPath(cxt, width, height, radius);
        cxt.fillStyle = fillColor || "#000";
        //若是给定了值就用给定的值否则给予默认值  
                cxt.fill();
        cxt.restore();
    },
    drawRoundRectPath(cxt, width, height, radius) {
        cxt.beginPath(0);
        //从右下角顺时针绘制，弧度从0到1/2PI  
                cxt.arc(width - radius, height - radius, radius, 0, Math.PI / 2);
        //矩形下边线  
                cxt.lineTo(radius, height);
        //左下角圆弧，弧度从1/2PI到PI  
                cxt.arc(radius, height - radius, radius, Math.PI / 2, Math.PI);
        //矩形左边线  
                cxt.lineTo(0, radius);
        //左上角圆弧，弧度从PI到3/2PI  
                cxt.arc(radius, radius, radius, Math.PI, Math.PI * 3 / 2);
        //上边线  
                cxt.lineTo(width - radius, 0);
        //右上角圆弧  
                cxt.arc(width - radius, radius, radius, Math.PI * 3 / 2, Math.PI * 2);
        //右边线  
                cxt.lineTo(width, height - radius);
        cxt.closePath();
    },
    /**该方法用来绘制圆角矩形 
*@param cxt:canvas的上下文环境 
*@param x:左上角x轴坐标 
*@param y:左上角y轴坐标 
*@param width:矩形的宽度 
*@param height:矩形的高度 
*@param radius:圆的半径 
*@param lineWidth:线条粗细 
*@param strokeColor:线条颜色 
**/
    strokeRoundRect(cxt, x, y, width, height, radius, /*optional*/ lineWidth, /*optional*/ strokeColor) {
        //圆的直径必然要小于矩形的宽高 
        if (2 * radius > width || 2 * radius > height) {
            return false;
        }
        cxt.save();
        cxt.translate(x, y);
        //绘制圆角矩形的各个边 
                this.drawRoundRectPath(cxt, width, height, radius);
        cxt.lineWidth = lineWidth || 2;
        //若是给定了值就用给定的值否则给予默认值2 
                cxt.strokeStyle = strokeColor || "#000";
        cxt.stroke();
        cxt.restore();
    }
});